Set Default Values for Variables in Bash Scripts

This post introduces some useful snippets and grammars in Bash shell for scripting to set default values.

The family consists of various grammars.

${var:-default}
If var is unset or is an empty string, then return default, otherwise unchanged. It does not modify the value of var.
${var-default}
Only if var is unset, then return default. If var is an empty string, the final value is still an empty string. It does not modify the value of var.
${var:=word}
If var is unset or empty, set var to word, and then return word.
${var:?error_log}
If var is unset or empty, output error_log to stderr and exits the script.
${var:+word}
If var is set and non-empty, return word, otherwise return empty string.
${var+word}
If var is set (even if it’s an empty string), return word.

Date: 2026-09-23 Wed

Author: ArcaLunar